//
//  MyViewController.m
//  Koala_Fm
//
//  Created by dllo on 16/1/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MyViewController.h"
#import "MyTableViewCell.h"
#import "LoginViewController.h"
#import "MyModel.h"
#import "HmViewController.h"
#import "ErweimaViewController.h"
@interface MyViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UIButton *button;
@property(nonatomic, retain)UIView *header;
@property(nonatomic, retain)NSMutableArray *dataArr;
@property(nonatomic, retain)UILabel *cacheLable;
@property(nonatomic, assign)BOOL isplay;
@property(nonatomic, retain)NSIndexPath *indexPath;// 记录清除缓存的下标
@property(nonatomic, retain)NSMutableArray *arr;
#define W self.view.bounds.size.width/375
#define H self.view.bounds.size.height/667
@end

@implementation MyViewController
- (void)dealloc
{
    [_tableView release];
    [_button release];
    [_header release];
    [_cacheLable release];
    [_dataArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
   [UIColor redColor];
    //    导航栏颜色
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationItem.title = @"我的";
    
       // tableView设置
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    /** 设置头部区域 **/
        [self headers];
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    /** 头像按钮**/
    _button.frame = CGRectMake(130*W, 50*H, 100, 100);
    self.button.backgroundColor = [UIColor cyanColor];
//    [self.button addTarget:self action:@selector(butt) forControlEvents:UIControlEventTouchUpInside];
    [_header addSubview:_button];
    [self.button setBackgroundImage:[UIImage imageNamed:@"tx@2x.jpg"] forState:UIControlStateNormal];
    
    
     /** 按钮切圆 **/
    _button.layer.cornerRadius = 50.0;
    _button.layer.borderWidth = 1.0;
    _button.layer.borderColor = [UIColor clearColor].CGColor;
    _button.clipsToBounds = TRUE;
   
    [_tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"cell"];
    
     // 数据处理
    
    self.dataArr = [@[@"我的收藏", @"清除缓存", @"夜间模式",@"扫一扫", @"消息推送"]mutableCopy];
    
    self.arr = [@[]mutableCopy];
//    [_tableView reloadData];
    
    
    /** 导航栏隐藏设置 **/
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        
        self.automaticallyAdjustsScrollViewInsets = NO;// 取消scrollview的内容自动调整
        
        UIEdgeInsets insets = self.tableView.contentInset;//tableView边界预留
        insets.top = self.navigationController.navigationBar.bounds.size.height;
        // 让上边界的预留值和导航栏相等
        
        self.tableView.contentInset = insets;
        // 把修改后的边界预留值赋值给tableView
        self.tableView.scrollIndicatorInsets = insets;//滚动指标点到滚动视图的边缘的距离
        
    }
    
    self.tableView.frame = CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height);
    
}

#pragma mark - 头部区域
- (void)headers{
    self.header = [[UIView alloc]initWithFrame:CGRectMake(0, 30, 0, 200)];
        _header.backgroundColor = [UIColor redColor];
    _tableView.tableHeaderView = _header;
    [_header release];
}
//// button点击方法
//- (void)butt{
//    NSLog(@"");
//    LoginViewController *login = [[LoginViewController alloc]init];
//    [self.navigationController pushViewController:login animated:YES];
//}
//// 分区数
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 2;
//}

// 分区头
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

//}


#pragma mark - tableView协议设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.row == 1) {
        //创建缓存显示
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        //获取缓存大小。。
        CGFloat fileSize = [self folderSizeAtPath:cachPath];
        self.cacheLable = [[UILabel alloc]initWithFrame:CGRectMake(280, 0, 80, 50)];
          _cacheLable.text = [NSString stringWithFormat:@"%.2fMB",fileSize];
        _cacheLable.textAlignment = 2;
        cell.accessoryView = _cacheLable;
        [_cacheLable release];

    }
   
    if (indexPath.row == 2) {
        // 添加开关
        UISwitch *witch = [[UISwitch alloc]initWithFrame:CGRectMake(280, 0, 80, 50)];
        witch.backgroundColor = [UIColor whiteColor];
        
//        [witch release];
        // 开状态下的颜色
        witch.onTintColor = [UIColor redColor];
        // 关状态下的颜色
//        witch.thumbTintColor = [UIColor blueColor];
        //witch  添加到cell 上
        cell.accessoryView = witch;
        // 添加事件
        [witch addTarget:self action:@selector(witchAction:) forControlEvents:UIControlEventValueChanged];
    }

    
    cell.lable.text = _dataArr[indexPath.row];
    return cell;
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    // 清除缓存
    if (indexPath.row == 1) {
        [self myClearCacheAction];
        self.indexPath = indexPath;
    }
    if (indexPath.row == 0) {
        HmViewController *hm =[[HmViewController alloc]init];
    [self.navigationController pushViewController:hm animated:YES];
    }
    if (indexPath.row == 4) {
    [MyViewController registerLocalNotification:4]; // 4秒后
    }
    // 扫一扫点击方法
    if (indexPath.row == 3) {
        ErweimaViewController *erweima = [[ErweimaViewController alloc]init];
        // 模态动画
        erweima.modalTransitionStyle = 1;
        // 模态跳转页面
        [self presentViewController:erweima animated:YES completion:^{
            // 跳转后执行
        }];
        
        
    }
    
}

// 设置本地通知
+ (void)registerLocalNotification:(NSInteger)alertTime {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
    NSLog(@"fireDate=%@",fireDate);
    
    notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知内容
    notification.alertBody =  @"精彩能容,不容错过";
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"更多精彩能容,敬请欣赏" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSDayCalendarUnit;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
// 取消某个本地推送通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key {
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}



// 开关触发方法
- (void)witchAction:(UISwitch *)open{
    NSLog(@"jskodjoasdpasdpa");
    if (!_isplay) {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"nightCome" object:nil userInfo:nil];
    }else{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dayCome" object:nil userInfo:nil];
    }
    
    _isplay = !_isplay;
}

#pragma mark - 计算缓存
- (CGFloat)folderSizeAtPath:(NSString *)folderPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) {
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString *fileName = nil;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
- (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
    
}
#pragma mark 清除缓存
-(void)myClearCacheAction{
    dispatch_async(
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    for (NSString *p in files) {
    NSError *error;
    NSString *path = [cachPath stringByAppendingPathComponent:p];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
    [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}
-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    //这里不能整体刷新 必须导航刷新 否则会使夜间模式出问题
    [_tableView reloadRowsAtIndexPaths:@[_indexPath] withRowAnimation:UITableViewRowAnimationTop];

}

// 导航栏隐藏触发方法
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0)
    {
        self.navigationController.navigationBar.hidden = YES;
    }
    
    else
    {
        self.navigationController.navigationBar.hidden= NO;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
